package com.jt.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RestTemplate loadBalancedRestTemplate;

    @Value("${spring.application.name:8090}")
    private String appname;

    @GetMapping("/consumer/doRestEcho1")
    public String doRestEcho1(){
        String url = "http://localhost:8081/provider/echo/8090";

        return restTemplate.getForObject(url,String.class);

    }

    @GetMapping("/consumer/doRestEcho2")
    public String doRestEcho2(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
        String url = String.format("http://%s:%s/provider/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appname);
        System.out.println("request url:" + url);
        return restTemplate.getForObject(url,String.class);

    }

    @GetMapping("/consumer/doRestEcho3")
    public String doRestEcho3(){
        String url = String.format("http://%s/provider/echo/%s","sca-provider",appname);

        return loadBalancedRestTemplate.getForObject(url,String.class);
    }
}
